<?php
/**
 * Created by b17
 * 3/5/12 6:17 PM
 */

class Admin_UserController extends G4T_AdminController
{
    /**
     * @var \Managers\Users
     */
    protected $_manager;

    const ITEMS_PER_PAGE = 20;

    public function init()
    {
        parent::init();
        $this->_manager = new \Managers\ProxyCacheManager(new \Managers\Users());
    }

    public function indexAction()
    {
        $users = $this->_manager->getList();
        $this->view->users = $users;

        $this->saveCurrentUrl();
    }

    public function viewAction()
    {
        $userId = $this->_getParam('id');
        $user = $this->_getUserOrRedirect($userId);
        $this->view->user = $user;

        $this->saveCurrentUrl();
    }

    public function adAction()
    {
        $userId = $this->_getParam('id');
        $user = $this->_getUserOrRedirect($userId);
        $this->view->user = $user;

        $adBuilder = new \Managers\Builder\AdBuilder();
        $adBuilder->setUser($userId);

        $total = $adBuilder->getTotal();
        $this->view->total = $total;
        $page = intval($this->_getParam('page'));
        $this->displayPaginantor($total, $page, self::ITEMS_PER_PAGE);

        $offset = $this->_getOffset($page, self::ITEMS_PER_PAGE);
        $adBuilder->setLimit(self::ITEMS_PER_PAGE, $offset);
        $ads = $adBuilder->getList();
        $this->view->ads = $ads;

        $this->saveCurrentUrl();
    }

    public function commentAction()
    {
        $userId = $this->_getParam('id');
        $user = $this->_getUserOrRedirect($userId);
        $this->view->user = $user;

        $commentBuilder = new \Managers\Builder\CommentBuilder();
        $commentBuilder->setUser($userId)
            ->setIsBlocked(false);

        $total = $commentBuilder->getTotal();
        $this->view->total = $total;
        $page = intval($this->_getParam('page'));
        $this->displayPaginantor($total, $page, self::ITEMS_PER_PAGE);

        $offset = $this->_getOffset($page, self::ITEMS_PER_PAGE);
        $commentBuilder->setLimit(self::ITEMS_PER_PAGE, $offset);
        $comments = $commentBuilder->getList();
        $this->view->comments = $comments;

        $this->saveCurrentUrl();
    }

    public function editcomAction()
    {
        $comment = $this->_getCommentOrRedirect($this->_getParam('id'));
        $this->view->comment = $comment;
        $form = $this->_getCommentForm();
        $form->populate($comment);
        $this->view->form = $form;

        if ($this->_request->isPost()) {
            if ($form->isValid($this->_getAllParams())) {
                $commentsManager = new \Managers\Comments();
                $entity = $commentsManager->updateByAdmin($form->getValues());
                $this->_flashMessenger->addMessage('Комментарий сохранен.', Lib_Flash::NOTICE, Lib_Flash::LATER);
                $url = $this->_getRedirectUrl();
                $this->_redirect($url);
            } else {
                $this->_flashMessenger->addMessage("Проверьте поля формы.", Lib_Flash::ERROR, Lib_Flash::LATER);
            }
        }
    }

    public function delcomAction()
    {
        $comment = $this->_getCommentOrRedirect($this->_getParam('id'));
        $commentsManager = new \Managers\Comments();
        $commentsManager->deleteByAdmin($comment['id']);
        $url = $this->_getRedirectUrl();
        $this->_flashMessenger->addMessage('Комментарий успешно удален.', Lib_Flash::NOTICE, Lib_Flash::LATER);
        $this->_redirect($url);
    }

    protected function _getCommentOrRedirect($commentId)
    {
        $commentBuilder = new \Managers\Builder\CommentBuilder();
        $commentBuilder->setId($commentId);
        $comment = $commentBuilder->getOne();
        if (!$comment) {
            $this->_flashMessenger->addMessage('Комментарий не найден.', Lib_Flash::ERROR, Lib_Flash::LATER);
            $this->_redirect('/admin/user');
        }
        return $comment;
    }

    protected function _getUserOrRedirect($userId)
    {
        $user = $this->_manager->getById($userId);
        if (!$user) {
            $this->_redirectNotFound($userId);
        }
        return $user;
    }

    private function _redirectNotFound($id)
    {
        $this->_flashMessenger->addMessage("Пользователь $id не найден.", Lib_Flash::ERROR, Lib_Flash::LATER);
        $this->_redirect('/admin/user');
    }

    private function _getCommentForm()
    {
        $formBuilder = \G4T\Form\FormBuilder::createFormBuilder(\Managers\Comments::TABLE)
            ->addField('id', 'hidden')
            ->addField('text', 'text', array('label' => 'Текст'))
            ->addField('submit', 'submit', array('label' => 'Сохранить', 'class' => 'btn btn-primary'));
        return $formBuilder->getForm();

    }

    public function removecomAction()
    {
        $commentBuilder = new \Managers\Builder\CommentBuilder();
        $commentBuilder->setUser($this->_getParam('id'));
        $commentManager = new \Managers\Comments();
        $commentManager->multiplyDeletes($commentBuilder->getResult());
        $this->_redirect($this->_getRedirectUrl());
    }

    public function removeadAction()
    {
        $adBuilder = new \Managers\Builder\AdBuilder();
        $adBuilder->setUser($this->_getParam('id'));
        $adManager = new \Managers\Ad();
        $adManager->multiplyDeletes($adBuilder->getResult());
        $this->_redirect($this->_getRedirectUrl());
    }

    public function lockAction()
    {
        $user = $this->_getUserOrRedirect($this->_getParam('id'));
        $this->_manager->changeLockFlag($user['id']);
        $url = $this->_getRedirectUrl();
        $this->_flashMessenger->addMessage('Пользователь успешно сохранен.', Lib_Flash::NOTICE, Lib_Flash::LATER);
        $this->_redirect($url);
    }

    protected function _getRedirectUrl()
    {
        $url = $this->getSavedUrl() ? : '/admin/user';
        return $url;
    }


}
